package com.lyon.demo.rpc.naming;

import com.lyon.demo.rpc.naming.core.ChildChannelHandler;
import com.lyon.demo.rpc.naming.dispatcher.DispatcherHandler;
import com.lyon.demo.rpc.naming.dispatcher.handler.ServiceRegisterHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.util.Properties;

/**
 * @author LeeYan9
 * @since 2022-04-15
 */
public class NamingController {

    @SneakyThrows
    public void start(Properties prop) {
        String port = prop.getProperty("port", "18880");

        NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(5);
        DispatcherHandler dispatcherHandler = new DispatcherHandler();
        dispatcherHandler.addProcess(0, new ServiceRegisterHandler());

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        final ChannelFuture sync = serverBootstrap
                .group(acceptGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChildChannelHandler(DispatcherHandler.instance()))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .bind(new InetSocketAddress("localhost",Integer.parseInt(port)))
                .sync();
        System.err.println("启动注册中心服务完成..");
    }
}
